<template>
  <el-card shadow="never">
    <template slot="header">
      <span>{{ title }}</span>
    </template>
    <div class="flex">
      <el-input v-model="inputText" size="small" class="flex-1 mr-1" />
      <el-button size="small" type="success" plain @click="add">添加</el-button>
    </div>
    <el-table
      :size="size"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="value" label="关键词"> </el-table-column>
      <el-table-column width="180">
        <template slot="header">
          <!-- <el-button type="info" plain :size="size" @click="clearAll"
            >清空</el-button
          > -->
          <div class="flex flex-row-reverse">
            <el-button
              type="danger"
              plain
              :size="size"
              :disabled="selection.length === 0"
              @click="removeSelected"
              >删除选中</el-button
            >
          </div>
        </template>
        <template slot-scope="scope">
          <div class="flex flex-row-reverse">
            <el-button
              type="danger"
              plain
              :size="size"
              @click="remove(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<script>
export default {
  name: 'Keywords',
  props: {
    title: {
      type: String,
      required: true,
    },
    size: {
      type: String,
      default: 'small',
    },
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      inputText: '',
      tableData: [],
      selection: [],
    }
  },
  watch: {
    tableData: {
      deep: true,
      handler(val) {
        this.$emit(
          'input',
          val.map((el) => el.value)
        )
      },
    },
  },
  methods: {
    handleSelectionChange(value) {
      this.selection = value
    },
    add() {
      if (!this.inputText) {
        this.$message.warning('需要选择省份')
        return
      }

      this.tableData.push({
        value: this.inputText,
      })
    },
    /**
     * 清除
     */
    clearAll() {
      this.tableData = []
    },
    remove(row) {
      this.tableData = this.tableData.filter((el) => el.value !== row.value)
    },
    removeSelected() {
      if (this.selection.length === 0) {
        this.$message.warning('请先勾选数据')
        return
      }
      this.tableData = this.tableData.filter(
        (el) => this.selection.indexOf(el) === -1
      )
    },
  },
}
</script>
